package com.pf.business.service.impl;

import com.pf.business.service.RedisService;
import com.pf.utils.RedisUtils;
import org.springframework.stereotype.Service;

/**
 * @author PF
 * @date 2021/5/15 14:01
 * @Version 1.0
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Override
    public void sendSmsVerificationCode(String mobile) {
        if (!RedisUtils.setIfAbsent("lock-" + mobile, mobile, 1)) {
            throw new RuntimeException("等待。。。。。。");
        }

        // 校验规则1：一分钟一个手机号只能发送一次验证码
        String keyInOneMin = "oneMin-" + mobile;
        final int smsExpireDiff = 120;
        if (RedisUtils.get(keyInOneMin) != null && RedisUtils.getExpireTime(keyInOneMin) > smsExpireDiff) {
            throw new RuntimeException("一分钟一个手机号只能发送一次验证码！");
        }

        // 校验规则2：一个手机号1天内只能发送10条短信息
        String key = "checkNums-" + mobile;
        Integer nums = RedisUtils.get(key, Integer.class);
        if (nums != null && nums.intValue() >= 10) {
            throw new RuntimeException("一个手机号一天内只能发送10条短信！手机号：" + mobile);
        }

        // 发送短信
        System.out.println(">>>>>>>>>>>模拟发送短信操作");
        /*try{
            Thread.sleep(20);
        }catch (Exception e){
            e.printStackTrace();
        }*/

        // 将该key存入redis中（过期时间默认180秒）
        RedisUtils.set(keyInOneMin, mobile, 180);

        // 将发送短信次数累加1
        RedisUtils.incr(key);

    }
}
